<!--产品配置-->
<template>
  <div class="product-config">
    <div class="tabs" :class="[{'tabs2': wiredNetwork == 0}]">
      <div
        v-for="tab in wiredNetwork === 1 ? tabs2 : tabs"
        :key="tab.index"
        class="tab-pane"
        :class="[{ 'tab-active': activeName === tab.index }, getClassName(tab.index), {'tabs2': wiredNetwork == 0}]"
        @click="handleTabs(tab.index)">
        <div>{{ tab.title }}</div>
      </div>
    </div>
    <div class="contain-wrap">
      <div class="contain">
        <div v-show="activeName === 1" v-loading="loading" class="peiwang">
          <el-form ref="form" class="content" :model="formData" label-width="80px" label-position="left">
            <el-form-item label="指引说明">
              <el-input
                v-show="!editStatus"
                v-model="formData.cnDescribe"
                type="textarea"
                maxlength="200"
                show-word-limit
                :rows="6"></el-input>
              <div v-show="editStatus" class="app-text">{{ formData.cnDescribe || '-' }}</div>
            </el-form-item>
            <el-form-item label="产品图片" class="form-item-img" :class="[{ 'no-edit-item': editStatus }]">
              <div v-show="!editStatus" class="product-img">
                <el-upload
                  class="upload-img"
                  action="/admin/sys-file/upload"
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeUpload">
                  <img v-if="formData.pictureUrl" :src="uploadUrl || formData.pictureUrl" class="uploaded-img">
                  <div v-else>
                    <i class="iconfont icon-shangchuantupian"></i>
                    <div class="text">点击上传</div>
                  </div>
                </el-upload>
                <!-- <div class="img-rule">
                  <p>尺寸：1080*1080px</p>
                  <p>格式：png</p>
                  <p>大小：100kb以内</p>
                </div> -->
              </div>
              <div v-show="editStatus">
                <img v-if="formData.pictureUrl" :src="uploadUrl || formData.pictureUrl" alt="">
                <span v-else>-</span>
              </div>
            </el-form-item>
          </el-form>

          <div class="app">
            <div class="title">APP内预览效果</div>
            <div class="display-area">
              <div class="area-title">网络配置</div>
              <div class="desc" v-html="formattedText"></div>
              <div v-if="!editStatus" class="img">
                <img v-if="uploadUrl || formData.pictureUrl" :src="uploadUrl || formData.pictureUrl" alt="">
              </div>
              <div v-if="editStatus" class="img">
                <img v-if="formData.pictureUrl" :src="formData.pictureUrl" alt="">
              </div>
            </div>
          </div>
        </div>
        <div v-show="activeName === 2" v-loading="loading" class="youxian">
          <el-form ref="form" class="content" :model="formWiredData" label-width="80px" label-position="left">
            <el-form-item label="指引说明">
              <el-input
                v-show="!editStatus"
                v-model="formWiredData.cnDescribe"
                type="textarea"
                maxlength="200"
                show-word-limit
                :rows="6"></el-input>
              <div v-show="editStatus" class="app-text">{{ formWiredData.cnDescribe || '-' }}</div>
            </el-form-item>
            <el-form-item label="产品图片" class="form-item-img" :class="[{ 'no-edit-item': editStatus }]">
              <div v-show="!editStatus" class="product-img">
                <el-upload
                  class="upload-img"
                  action="/admin/sys-file/upload"
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeUpload">
                  <img v-if="formWiredData.pictureUrl" :src="uploadWiredUrl || formWiredData.pictureUrl" class="uploaded-img">
                  <div v-else>
                    <i class="iconfont icon-shangchuantupian"></i>
                    <div class="text">点击上传</div>
                  </div>
                </el-upload>
                <div class="img-rule">
                  <p>尺寸：1080*1080px</p>
                  <p>格式：png</p>
                  <p>大小：100kb以内</p>
                </div>
              </div>
              <div v-show="editStatus">
                <img v-if="formWiredData.pictureUrl" :src="formWiredData.pictureUrl" alt="">
                <span v-else>-</span>
              </div>
            </el-form-item>
          </el-form>

          <div class="app">
            <div class="title">APP内预览效果</div>
            <div class="display-area">
              <div class="area-title">网络配置</div>
              <div class="desc" v-html="formattedTextWired"></div>
              <div v-if="!editStatus" class="img">
                <img v-if="uploadWiredUrl || formWiredData.pictureUrl" :src="uploadWiredUrl || formWiredData.pictureUrl" alt="">
              </div>
              <div v-if="editStatus" class="img">
                <img v-if="formWiredData.pictureUrl" :src="formWiredData.pictureUrl" alt="">
              </div>
            </div>
          </div>
        </div>
        <div v-show="activeName === 3" class="scene">
          <el-form class="func-form" :model="funcForm">
            <div class="condition">
              <div class="title">条件设置</div>
              <div class="desc">在App中可以作为场景条件进行选择</div>

              <el-form-item>
                <el-checkbox-group v-model="checkboxConditionValue" @change="handleCheckedCondition">
                  <el-checkbox
                    v-for="item in sceneConditionData"
                    :key="item.showId"
                    :label="item.showId"
                    :disabled="editStatus">{{ item.name
                    }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
            <div class="action">
              <div class="title">动作设置</div>
              <div class="desc">在App中可以作为场景动作进行选择</div>
              <el-form-item>
                <el-checkbox-group v-model="checkboxActionValue" @change="handleCheckedAction">
                  <el-checkbox
                    v-for="item in sceneActionData"
                    :key="item.showId"
                    :label="item.showId"
                    :disabled="editStatus">{{ item.name
                    }}</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
          </el-form>
        </div>
        <div v-show="activeName === 4" class="json-editor">
          <!-- <div class="editor-container">
            <div ref="lineNumbers" class="line-numbers">
              <span v-for="n in lineCount" :key="n">{{ n }}</span>
            </div>
            <textarea
              ref="jsonTextarea"
              v-model="jsonText"
              class="json-textarea"
              :readonly="editStatus"
              @input="handleInput"
              @scroll="handleScroll"
            ></textarea>
          </div> -->
          <el-form :model="formDataJson" label-width="50px" label-position="left">
            <div v-for="(item, index) in formDataJson.items" :key="index">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="Key">
                    <el-input v-model="item.key" placeholder="请输入键" :disabled="editStatus"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="14">
                  <el-form-item label="Value">
                    <el-input v-model="item.stringValue" type="textarea" placeholder="请输入值" class="text-value" :disabled="editStatus" @input="updateValue(item)"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-button v-if="formDataJson.items.length > 1" type="danger" :disabled="editStatus" @click.prevent="removeItem(index)">删除</el-button>
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" :disabled="editStatus" @click.prevent="addItem">新增</el-button>
          </el-form>
        </div>
      </div>
      <div class="btn">
        <el-button
          v-show="editStatus"
          :disabled="rolesCode === 'SALE'"
          type="primary"
          size="14"
          @click="onEdit">编辑</el-button>
        <el-button v-show="!editStatus" size="14" @click="handleClose">取消</el-button>
        <el-button v-show="!editStatus" type="primary" size="14" @click="onSubmit">保存</el-button>
      </div>
    </div>
  </div></template>
<script>
import { getNetConfig, addNetConfig, getSceneConfig, addSceneConfig, propertiesEventBy, queryProduct, saveProductTextArea, productTextArea } from '@/api/product/product-details'
import { mapGetters } from 'vuex'
import store from '@/store'
export default {
  name: "productionConfig",
  data() {
    return {
      checkboxConditionValue: [], // 场景条件选中数据
      checkboxActionValue: [], // 场景动作选中数据
      headers: {
        'TENANT-ID': store.getters.userInfo.tenantId,
        Authorization: 'Bearer ' + store.getters.access_token
      },
      activeName: 1, // tab显示 状态
      tabs: [
        { index: 1, title: "配网指引" },
        { index: 3, title: "场景设置" },
        { index: 4, title: "物模型文本域" }
      ],
      tabs2: [
        { index: 1, title: "配网指引" },
        { index: 2, title: "有线联网指引" },
        { index: 3, title: "场景设置" },
        { index: 4, title: "物模型文本域" }
      ],
      formData: {
        cnDescribe: '', // 指引说明
        pictureUrl: '' // 产品图片
      },
      formWiredData: {
        cnDescribe: '', // 指引说明
        pictureUrl: '' // 产品图片
      },
      formattedText: '', // APP内显示文案
      formattedTextWired: '',
      editStatus: true, // 编辑状态
      funcForm: { // 功能定义表单数据
        condition: '',
        action: ''
      },
      uploadUrl: '', // 产品图片
      uploadWiredUrl: '',
      sceneConditionData: [], // 场景条件设置数据
      sceneActionData: [], // 场景条件设置数据
      loading: true,
      wiredNetwork: 0,
      jsonText: '',
      lineCount: 1,
      formDataJson: {
        items: [
          { key: '', value: '', stringValue: '' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['rolesCode'])
  },
  watch: {
    'formData.cnDescribe'(newValue) {
      // 监听 textareaValue 的变化
      this.formattedText = newValue.replaceAll('\n', '<br>')
    },
    'formWiredData.cnDescribe'(newValue) {
      // 监听 textareaValue 的变化
      this.formattedTextWired = newValue.replaceAll('\n', '<br>')
    }
  },
  created() {
    this.productId = this.$route.query.productId
    this.queryDefineList()
    this.queryNetConfigList()
    this.querySceneConfigList()
    this.queryProductTextArea()
  },
  methods: {
    addItem() {
      this.formDataJson.items.push({ key: '', value: '', stringValue: '' })
    },
    removeItem(index) {
      this.formDataJson.items.splice(index, 1)
    },
    // 更新 value
    updateValue(item) {
      try {
        // 尝试将 stringValue 转换为对象或数组
        item.value = JSON.parse(item.stringValue)
      } catch (e) {
        // 如果转换失败，说明是普通字符串、数字或布尔值
        item.value = item.stringValue
      }
    },
    // 产品信息数据
    queryDefineList() {
      const params = {
        productId: this.productId
      }
      queryProduct(params).then(res => {
        const { data } = res.data
        this.wiredNetwork = data.wiredNetwork
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },

    // tab 切换
    handleTabs(key) {
      this.activeName = key
      if (this.tabs.length === 3) {
        if (this.activeName !== 3) {
          this.queryNetConfigList()
        } else {
          this.querySceneConfigList()
        }
      } else {
        if (this.activeName !== 2) {
          this.queryNetConfigList()
        } else {
          this.querySceneConfigList()
        }
      }
    },
    // 编辑
    onEdit() {
      this.editStatus = !this.editStatus
    },
    // 获取物模型文本域
    queryProductTextArea() {
      this.editStatus = true
      const params = {
        productId: this.productId
      }
      productTextArea(params).then(res => {
        if (res.data.data.textAreaVOList.length > 0) {
          this.formDataJson.items = res.data.data.textAreaVOList.map(item => {
            const value = item.value
            if (typeof value === 'object') {
            // 如果 value 是对象或数组，转换为字符串
              item.stringValue = JSON.stringify(value, null, 2)
            } else {
            // 否则直接赋值
              item.stringValue = value
            }
            return item
          })
        }
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 获取场景数据
    querySceneConfigList() {
      propertiesEventBy(this.productId).then(res => {
        this.sceneConditionData = res.data.data.filter(item => {
          return item.sceneCondition
        })
        this.sceneActionData = res.data.data.filter(item => {
          return item.sceneAction
        })
        this.querySceneCheckedList()
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // // 检验是否为json
    // isValidJSON(str) {
    //   try {
    //     // 使用 JSON.parse 检查字符串是否为有效的 JSON
    //     const parsed = JSON.parse(str)

    //     // 检查解析结果的数据类型是否为对象或数组
    //     return parsed !== null && typeof parsed === 'object' || Array.isArray(parsed)
    //   } catch (e) {
    //     return false
    //   }
    // },
    /**
     * 保存
     */
    onSubmit() {
      if (this.activeName === 3) {
        const parmas = {
          productId: this.productId,
          conditionDpIds: [...new Set(this.checkboxConditionValue)],
          actionDpIds: [...new Set(this.checkboxActionValue)]
        }
        addSceneConfig(parmas).then(res => {
          this.querySceneCheckedList()
        }).catch(err => {
          this.$message.error(err.message)
        })
      } else if (this.activeName === 4) {
        const parmas = {
          productId: this.productId,
          textAreaBOList: this.formDataJson.items
        }
        saveProductTextArea(parmas).then(res => {
          this.queryProductTextArea()
        }).catch(err => {
          this.$message.error(err.message)
        })
      } else {
        const parmas = {
          pictureUrl: this.activeName === 1 ? this.formData.pictureUrl : this.formWiredData.pictureUrl,
          cnDescribe: this.activeName === 1 ? this.formData.cnDescribe : this.formWiredData.cnDescribe,
          productId: this.productId,
          type: this.activeName === 1 ? 'wireless' : 'wired'
        }
        addNetConfig(parmas).then(res => {
          this.queryNetConfigList()
        }).catch(err => {
          this.$message.error(err.message)
        })
      }
    },
    // 取消
    handleClose() {
      this.queryNetConfigList()
      this.queryProductTextArea()
      this.editStatus = true
    },
    // 获取配网指引数据
    queryNetConfigList() {
      this.loading = true
      const parmas = {
        productId: this.productId,
        type: this.activeName === 1 ? 'wireless' : 'wired'
      }
      getNetConfig(parmas).then(res => {
        if (res.data.data !== null) {
          if (this.activeName === 1) {
            this.formData.pictureUrl = res.data.data.pictureUrl
            this.formData.cnDescribe = res.data.data.cnDescribe
          } else if (this.activeName === 2) {
            this.formWiredData.pictureUrl = res.data.data.pictureUrl
            this.formWiredData.cnDescribe = res.data.data.cnDescribe
          }
        }
        this.editStatus = true
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 获取场景选中数据
    querySceneCheckedList() {
      getSceneConfig(this.productId).then(res => {
        this.checkboxConditionValue = res.data.data.conditionDpIds || []
        this.checkboxActionValue = res.data.data.actionDpIds || []
        this.editStatus = true
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 产品图片上传成功
    handleAvatarSuccess(res, file) {
      if (this.activeName === 1) {
        this.uploadUrl = URL.createObjectURL(file.raw)
        this.formData.pictureUrl = res.data.url
      } else {
        this.formWiredData.pictureUrl = res.data.url
        this.uploadWiredUrl = URL.createObjectURL(file.raw)
      }
    },
    // 产品图片上传之前
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        // 校验图片格式是否为png
        const isPng = file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg'
        if (!isPng) {
          this.$message.error('只能上传png/jpg/jpeg格式的图片')
          return
        }

        // 使用FileReader获取图片尺寸
        const reader = new FileReader()
        reader.onload = (e) => {
          const image = new Image()
          image.onload = () => {
            // // 校验图片尺寸是否为1080x1080
            // const width = image.width
            // const height = image.height
            // if (width === 1080 && height === 1080) {
            //   // 校验图片大小是否小于100M
            //   if (file.size <= 100 * 1024 * 1024) {
            //     resolve(file)
            //   } else {
            //     this.$message.error('图片大小不能超过100M')
            //   }
            // } else {
            //   this.$message.error('图片尺寸必须为1080x1080')
            // }
            // 校验图片大小是否小于100M
            if (file.size <= 100 * 1024 * 1024) {
              resolve(file)
            } else {
              this.$message.error('图片大小不能超过100M')
            }
          }
          image.src = e.target.result
        }
        reader.readAsDataURL(file)
      })
    },
    // 条件设置
    handleCheckedCondition(val) {
      this.checkboxConditionValue = val
    },
    // 动作设置
    handleCheckedAction(val) {
      this.checkboxActionValue = val
    },
    getClassName(index) {
      // 根据 index 的值返回相应的类名
      if (index === 1) {
        return 'tab-active1'
      } else if (index === 2) {
        return 'tab-active2'
      } else if (index === 3) {
        return 'tab-active3'
      } else if (index === 4) {
        return 'tab-active4'
      }
      return '' // 如果 index 不是 1、2 或 3，则不返回任何类名
    }
  }
}
</script>
<style lang="scss" scoped>
.product-config {
  font-size: 14px;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  height: 100%;

  .tabs {
    display: flex;
    align-items: center;
    height: 34px;
    border: 1px solid #dedede;
    border-radius: 4px;
    width: 472px;
    font-size: 14px;
    font-weight: 600;
    color: #252525;

    .tab-pane {
      width: 104px;
      height: 34px;
      line-height: 34px;
      text-align: center;
    }

    .tab-pane:nth-child(2),
    .tab-pane:last-child {
      width: 132px;
    }

    .tab-active1 {
      border-radius: 4px 0px 0px 4px;
    }

    .tab-active4 {
      border-radius: 0px 4px 4px 0px;
    }

    .tab-active {
      background: #275fe8;
      color: #ffffff;
    }
  }

  .tabs2 {
    width: 340px;

    .tab-pane:nth-child(2) {
      width: 104px;
    }

    .tab-pane:last-child {
      width: 132px;
    }
  }

  .contain-wrap {
    flex-grow: 1;

    .contain {
      height: calc(100% - 76px);
    }
  }

  .peiwang,
  .youxian {
    display: flex;
    position: relative;
    height: 100%;

    .content {
      width: calc(100% - 594px);
      margin-top: 36px;

      .app-text {
        word-wrap: break-word;
      }

      img {
        width: 100px;
        height: 100px;
      }
    }

    .app {
      margin-left: 220px;

      .title {
        text-align: center;
        margin-bottom: 8px;
        font-weight: 400;
        color: #808080
      }

      .display-area {
        width: 245px;
        height: 482px;
        background: #ffffff;
        border-radius: 30px;
        opacity: 1;
        border: 6px solid #3c3c3c;
        overflow: hidden;

        .area-title {
          font-weight: 500;
          color: #000000;
          text-align: center;
          margin-top: 12px;
          margin-bottom: 42px;
        }

        .desc {
          padding: 0 18px;
          font-weight: 400;
          color: #222222;
          line-height: 20px;
          font-size: 12px;
        }

        .img {
          margin-top: 67px;
          text-align: center;

          img {
            width: 68px;
            height: 68px;
          }
        }
      }
    }
  }

  .scene {
    margin-left: 40px;
    position: relative;
    height: 100%;

    .condition,
    .action {
      padding-top: 39px;

      .title {
        font-weight: 600;
        color: #000000;
      }

      .desc {
        font-weight: 400;
        color: #7A7B80;
        margin-top: 4px;
        margin-bottom: 24px;
        font-size: 12px;
      }
    }

    .action {
      padding-top: 23px;
    }

    .el-checkbox {
      margin-right: 30px;
    }
  }

  .product-img {
    display: flex;

    .upload-img {
      .uploaded-img {
        width: 80px;
        height: 80px;
      }

      ::v-deep .el-upload {
        width: 80px;
        height: 80px;
        border: 1px dashed #DEDEDE;
        border-radius: 4px;
        font-weight: 400;
        color: #808080;
      }

      .icon-shangchuantupian {
        width: 32px;
        height: 32px;
        font-size: 32px;
        position: absolute;
        top: 11px;
        left: 25px;
      }

      .text {
        margin-top: 40px;
      }
    }

    .img-rule {
      font-size: 12px;
      font-weight: 400;
      color: #808080;
      margin-left: 15px;

      p {
        height: 14px;
        line-height: 14px;
      }
    }
  }

  .func-form .el-radio {
    display: block;
    margin-bottom: 16px;
  }

  .func-form ::v-deep .el-radio .el-radio__label {
    font-size: 12px;
  }

  .btn {

    .el-button+.el-button {
      margin-left: 0px;
      margin-right: 16px;
    }

    .copy-btn {
      margin-left: 16px !important;
    }
  }

  .json-editor {
    width: 100%;
    height: calc(100vh - 370px); /* 固定高度 */
    overflow-x: hidden;  /* 隐藏多余内容 */
    // position: relative;
    margin: 20px 0;
    // border: 1px solid black;

    .text-value ::v-deep .el-textarea__inner {
      height: 120px;
    }

    .editor-container {
      display: flex;
      height: calc(100% - 30px);
      overflow: hidden;
      border: 1px solid #ccc; /* 可选：用于视觉上的清晰 */
      border-radius: 4px;
      margin: 30px 0;

      .line-numbers {
        width: 50px; /* 根据行号的宽度调整 */
        text-align: center;
        font-family: monospace;
        color: #999;
        overflow: hidden; /* 确保行号区域不滚动自身 */
        padding-top: 10px; /* 与textarea的padding保持一致 */
        box-sizing: border-box;
        border-right: 1px solid #ccc;

        span {
          display: block;
          line-height: 1.5em; /* 与textarea的行高匹配 */
        }
      }

      .json-textarea {
        flex-grow: 1;
        height: 100%;
        padding: 10px;
        font-family: monospace;
        border: none;
        resize: none;
        outline: none;
        overflow: auto; /* 启用滚动 */
        line-height: 1.5em; /* 与行号的行高匹配 */
        margin-left: 10px; /* 留出行号的宽度 */
        box-sizing: border-box;
      }
    }
  }
}

::v-deep .el-form-item__label {
  font-weight: 600;
  color: #808080;
}

::v-deep .el-form-item--small.el-form-item {
  margin-bottom: 32px;
}

:v-deep .el-textarea .el-input__count {
  right: 20px;
  bottom: 0;
}
</style>
